package org.argus.common.redis.configure;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Redisson 配置
 * @Author 刘文/Cliff Liu
 * @Date 2024/5/18
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.redis", name = "host")
public class RedissonConfig {
    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    public RedissonClient redisson(RedisProperties redisProperties){
        // 目前只支持单个节点的redis配置，后面 集群 或 哨兵模式有需要再支持
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig.setAddress("redis://"+redisProperties.getHost()+":"+redisProperties.getPort());
        if (StringUtils.isNotBlank(redisProperties.getPassword())) {
            singleServerConfig.setPassword(redisProperties.getPassword());
        }
        singleServerConfig.setKeepAlive(true);
        singleServerConfig.setDatabase(redisProperties.getDatabase());
        singleServerConfig.setClientName(applicationName);
        return Redisson.create(config);
    }

}
